<?php

namespace app\api\controller;

use think\Db;

use app\common\controller\Logined;
use app\common\service\TranslateService;
//公告
class Notice extends Logined{

	/*
	获取公告列表
	*/
	public function getNotice(){
		$uid = $this->uid;
		if(empty($uid)){
			$this->retData(1,'缺少参数');
		}
		$data = model('NoticeModel')->getNoticeList();
		if($data){
			foreach ($data as $key => $val) {
				//翻译
				$data[$key]['title'] = TranslateService::baiduApi($val['title'],$this->lang);
				$data[$key]['content'] = TranslateService::baiduApi($val['content'],$this->lang);
				$data[$key]['is_read'] = Db::table('tp_notice_judge')->where('nid',$val['id'])->where('uid',$uid)->find()?1:2;
			}
			$this->retData(0,'success',$data);
		} else {
			$this->retData(0,'fail');
		}
	}

	/*
	公告详细
	*/
	public function noticeDetail(){
		$id  = P('id');
		$uid = $this->uid;
		if(empty($id) || empty($uid)){
			$this->retData(1,'缺少参数');
		}
		$is_read = Db::table('tp_notice_judge')->where('nid',$id)->where('uid',$uid)->find();
		if(!$is_read){
			Db::table('tp_notice_judge')->insert([
				'nid'=>$id,
				'uid'=>$uid
			]);
		}
		$data = model('NoticeModel')->getDetail($id);
		if($data){
			//翻译
			$data['title'] = TranslateService::baiduApi($data['title'],$this->lang);
			$data['content'] = TranslateService::baiduApi($data['content'],$this->lang);
			$this->retData(0,'success',$data);
		} else {
			$this->retData(0,'fail');
		}
	}

	/*
	全部已读
	 */
	public function allRead(){
		$uid = $this->uid;
		if(empty($uid)){
			$this->retData(1,'缺少参数');
		}
		//全部
		$all_id = Db::table('tp_notice')->where('type',1)->column('id');
		//已读
		$readed = Db::table('tp_notice_judge')->where('uid',$uid)->column('nid');
		//未读
		$un_read = array_diff($all_id,$readed);
		if($un_read){
			foreach ($un_read as $key => $val) {
				$res = Db::table('tp_notice_judge')->insert([
					'nid'=>$val,
					'uid'=>$uid
				]);
			}
			$this->retData(0,'全部已读');
		} else{
			$this->retData(1,'全部已读');
		}
	}

	public function judge(){
		$uid = $this->uid;
		if(empty($uid)){
			$this->retData(1,'缺少参数');
		}
		//全部
		$all_id = Db::table('tp_notice')->where('type',1)->column('id');
		//已读
		$readed = Db::table('tp_notice_judge')->where('uid',$uid)->column('nid');
		//未读
		$un_read = array_diff($all_id,$readed);
		if(empty($un_read)){
			$this->retData(0,'success',1);
		} else {
			$this->retData(0,'success',2);
		}
	}
}